<template>
    <q-page class="page" style="background-color: #e7f0fb">
        <!-- <BackHeader v-if="!isApp && !useWxHook().isAnyirongMini()" title="机构申请" fixed bg="transparent" /> -->
        <div @click="showContact" class="flex items-center msg-text">
            <ScrollText bgColor="#fff" :text="msg"></ScrollText>
        </div>
        <div v-if="isShowResult" class="show-results">
            <div class="show-results-box">
                <img src="~/assets/images/shop/success-res-1.png" alt="">
                <div v-if="isFail" class="right-text">
                    <div class="right-text-title">目前暂无匹配机构</div>
                    <div class="right-text-tips">请耐心等待更多机构匹配，<span style="color: #FE2F74;">注意接听</span>机构来电</div>
                </div>
                <div v-else class="right-text">
                    <div class="right-text-title">机构匹配成功！</div>
                    <div class="right-text-tips">将立即与您电话联系，请<span style="color: #FE2F74;">注意接听</span></div>
                </div>
                <!-- <div @click="closeResults" class="close-img">
                    <img src="~/assets/images/shop/close.png" alt="">
                </div> -->
            </div>
        </div>
        <template v-if="prodList.length > 0 && !isMiniprogram">
            <div class="page-title" id="page-title">
                精选推荐
                <div class="page-title-tips">
                    根据资质为您精准匹配
                </div>
            </div>
            <div class="page-grid">
                <van-swipe :loop="false">
                    <van-swipe-item v-for="(swiperItem, index) in swiperItemList">
                        <div class="four-shop">
                            <div 
                                v-for="(item, swiperItemIndex) in swiperItem"
                                :key="index" 
                                class="four-shop-item"
                                :class="[ currentIndex == item.productId ? 'current-active' : '' ]"
                                :style="{backgroundColor: currentIndex == item.productId ? '#1277FF' : '#fff'}"
                                @click="changeCurrent(item.productId)"
                            >
                                <div v-if="item.productTitle" class="item-corner">
                                    {{ item.productTitle }}
                                </div>
                                <div class="item-head">
                                    <img :src="item.productLogo" alt="">
                                    <div>
                                        <div :style="{color: currentIndex == item.productId ? '#fff' : '#000'}">{{ item.productName }}</div>
                                        <div :style="{color: currentIndex == item.productId ? '#fff' : '#666666'}">{{ item.productLabel }}</div>
                                    </div>
                                </div>
                                <div class="item-body">
                                    <div 
                                        v-for="(cofItem, index) in itemConfig" 
                                        :index="index"
                                        :style="{ backgroundColor: currentIndex == item.productId ? 'rgba(255, 255, 255, 0.27)' : '#F4F6F9' }"
                                    >
                                        <div :style="{ color: currentIndex == item.productId ? 'rgba(255, 255, 255, 0.61)' : '#222222' }">
                                            {{ cofItem.name }}
                                        </div>
                                        <div v-if="cofItem?.formate" :style="{ color: currentIndex == item.productId ? '#FFFFFF' : '#1277FF' }">
                                            {{ cofItem.formate(item) }}
                                        </div>
                                        <div v-else :style="{ color: currentIndex == item.productId ? '#FFFFFF' : '#1277FF' }">
                                            {{ cofItem.key ? item?.[cofItem.key] : cofItem.text }}
                                        </div>
                                    </div>
                                </div>
                                <div @click="gotoPage(item)" class="item-bottom">
                                    立即申请
                                </div>
                            </div>
                            <div v-if="swiperItem.length == 1" class="temp"></div>
                        </div>
                    </van-swipe-item>
                    <template #indicator="{ active, total }">
                        <div style="width: 100%; display: flex; justify-content: center;">
                            <div class="custom-indicator" :style="{ width: `${total * 14}px` }">
                                <div :style="{ transform: `translateX(${ active * 14 }px)` }" class="custom-indicator-item"></div>
                            </div>
                        </div>
                    </template>
                </van-swipe>
            </div>
        </template>
        <div class="gzh" @click="gotoWxGZH">
            <img class="gzh-img" :src="gzhInfo?.gzhLogo" alt="">
            <div style="flex: auto;">
                <div class="gzh-text">
                    借钱额度审核通知
                    <div class="gzh-text-box">公众号</div>
                </div>
                <div class="gzh-tips">关注公众号了解额度调整最新动态</div>
            </div>
            <div style="width: 83px;">
                <q-btn label="关注" padding="none none" unelevated rounded class="full-width" style="
                    background-color: #0D5BFC;
                    color: #FFF;
                    height: 28px;
                    font-size: 14px;
                    font-weight: 600;
                " />
            </div>
        </div>
        <BackInfoDialog ref="BackInfoDialogRef" :prod-name="fristProd?.productName" :prod-img="fristProd?.productLogo"
            :is-customize-goto="fristProd ? true : false" @goto="gotoWaitPage" />
        <ContactDialog :isShowUI="false" ref="ContactDialogRef" />
        <UnionDialog ref="UnionDialogRef" @confirm="unionConfirm" />
        <ProdJumpDialog ref="ProdJumpDialogRef" />
        <Protocol ref="ProtocolRef"/>
    </q-page>
</template>

<script setup lang="ts">
import { prodClickCountApi } from "src/api/prod";
import { getConfigApi, gzhPageJumpInfoApi } from 'src/api/app';
import { ContactDialogInstance } from 'src/components/ContactDialog';
import { useWxHook } from 'src/hooks/wx_hooks';
import { computed, HtmlHTMLAttributes, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import ContactDialog from 'src/components/ContactDialog.vue';
import { getCacheApi, getLoanOverProductApi } from 'src/api/prod';
import { gotoProd, ProdItem, ResType } from '../prodList/prodList';
import ProdJumpDialog from 'src/components/ProdJumpDialog.vue';
import { ProdJumpDialogInstance } from 'src/components/ProdJump';
import BackInfoDialog from 'src/components/BackInfoDialog.vue';
import { BackInfoDialogInstance } from 'src/components/BackInfoDialog';
import UnionDialog from 'src/components/unionDialog/UnionDialog.vue';
import { UnionDialogInstance } from 'src/components/unionDialog/UnionDialog';
import { useMechanismStore } from "src/stores/mechanism-store";
import { getApiBOrderListApi } from "src/api/merchant";
import { APIBItem } from "src/types/apib";
import Protocol from '../mechanism/dialog/Protocol.vue';
import { ProtocolInstance } from '../mechanism/dialog/Protocol';
type sysConfig = {
    code: string;
    contentInfo: string;
    name: string;
};
type GzhRes = {
    gzhLogo: string,
    gzhName: string,
    gzhQrCode: string
}
enum ItemType {
    Half
}
interface ProdItemEX extends ProdItem{
    itemType?: ItemType,
    orderId?: string,
    infoId?: string
}
const isMiniprogram = useWxHook().isMiniprogram.value
const router = useRouter();
const route = useRoute();
const isApp = route.query.isApp as string;
const ContactDialogRef = ref<ContactDialogInstance>();
const tabListRef = ref<Array<HTMLDivElement | null>>([]);
const tabsRef = ref<HTMLDivElement | null>();
const decorationLeft = ref<string>("-100px");
const msg = ref("")
const currentTab = ref<number>(0)
const prodList = ref<Array<ProdItemEX>>([])
const gzhInfo = ref<GzhRes>()
const ProdJumpDialogRef = ref<ProdJumpDialogInstance>();
const BackInfoDialogRef = ref<BackInfoDialogInstance>();
const UnionDialogRef = ref<UnionDialogInstance>();
const ProtocolRef = ref<ProtocolInstance>();
const isShowResult = ref(true);
const currentIndex = ref("");
type ItemConfig = {
    name: string;
    key?: keyof ProdItem;
    text?: string;
    formate?: (item: ProdItem) => string;
};
const itemConfig: Array<ItemConfig> = [
    {
        name: '最高额度',
        formate: (item) => {
            return moneyFormat(Number(item.maxAmount))
        }
    },
    {
        name: '年化利率',
        key: 'rateAmountInfo',
    },
    {
        name: '放款速度',
        formate: (item) => {
            return item.speed || '24小时'
        }
    },
    {
        name: '贷款期限',
        formate: (item) => {
            return item.loanTime || '36期'
        }
    }
]
const swiperItemList = computed(() => {
  const chunkSize = 4;
  const result: ProdItem[][] = [];
  if (!prodList.value) return [];
  for (let i = 0; i < prodList.value.length; i += chunkSize) {
    const chunk = prodList.value.slice(i, i + chunkSize);
    result.push(chunk);
  }
  console.log(result)
  return result;
});
const isFail = computed(() => {
    return !!Number(route.query.isFail || 1);
});
const fristProd = computed(() => {
    return prodList.value[0]
})

onMounted(() => {
    window.history.pushState({ infoInputPage: true }, 'shop', window.location.href);
    window.addEventListener('popstate', popstateHandler);
    useMechanismStore().resetMatchData();
    getConfigMsg();
    getProdList();
})
onUnmounted(() => {
    window.removeEventListener('popstate', popstateHandler);
});
const initHalfMatchData = async () => {
  const res = await getApiBOrderListApi<{ dataList: APIBItem[] }>({});
  if(res.data?.dataList.length > 0){
    return {
      halfMatchSuccess: true,
      item: res.data?.dataList
    }
  }
  return {
    halfMatchSuccess: false,
  }
}
const moneyFormat = (money: number): string => {
    const tenThousand = money / 10000;
    const formattedValue = tenThousand % 1 === 0
        ? tenThousand.toString()
        : tenThousand.toFixed(2).replace(/\.?0+$/, '');
    return `${formattedValue}万元`;
}
const closeResults = () => {
    isShowResult.value = false
}
const popstateHandler = (e: PopStateEvent) => {
    BackInfoDialogRef.value?.show();
    setTimeout(() => {
        window.history.pushState({ infoInputPage: true }, 'shop', window.location.href);
    });
};
const getProdList = async () => {
    const res = await getLoanOverProductApi<ResType>({ sceneId: 5 });
    const resHalf = await initHalfMatchData();
    prodList.value = res.data.dataList;
    if(resHalf.halfMatchSuccess){
        const list: ProdItemEX[] = resHalf.item?.map((item) => {
            return {
                detailUrl: item.approveUrl,
                maxAmount: item.maxLoanAmount,
                productId: item.orderItemId,
                orderId: item.orderId,
                productLabel: item.companySubTitle,
                productLogo: item.companyLogo,
                productName: item.companyName,
                productTitle: item.companyTitle,
                rateAmountInfo: item.minRate,
                unionFlag: false,
                downloadFlag: 0, //是否在下载应用；1 下载；0 不下载
                jumpStatus: 0, // 1 跳 0 不跳
                backgroundLogo: '',
                privacy: [
                    { name: '', url: item.htmlContent || '' , key: ''}
                ],
                speed: '',
                loanTime: '',
                itemType: ItemType.Half,
                infoId: item.infoId
            }
        }) || []
        prodList.value = list.concat(prodList.value)
        console.log(prodList.value)
    }
    nextTick(() => {
        scrollToTarget();
        currentIndex.value = fristProd.value.productId;
    })
    console.log(res);
}
const tabClick = (index: number) => {
    const dom = tabListRef.value[index];
    currentTab.value = index
    if (dom && tabsRef.value) {
        tabsRef.value.scrollTo({ behavior: 'smooth', left: dom.offsetLeft - 20, })
        const tab = dom.getBoundingClientRect()
        decorationLeft.value = `${dom.offsetLeft + tab.width / 2 - 20}px`
    }
}
const showContact = () => {
    ContactDialogRef.value?.show()
}
const getConfigMsg = async () => {
    const res = await getConfigApi<sysConfig>({
        id: 5
    })
    msg.value = res.data.contentInfo;
    const gzhRes = await gzhPageJumpInfoApi<GzhRes>();
    gzhInfo.value = gzhRes.data;
    setTimeout(() => {
        nextTick(() => {
            tabClick(0)
        })
    }, 300)
}
const gotoWxGZH = () => {
    if (useWxHook().isMiniprogram.value) {
        return useWxHook().toWxMiniGZH();
    }
    return router.push({ path: '/wxfollow', query: route.query });
};
const clearProdItem = (prodItem: ProdItem) => {
    prodList.value = prodList.value.filter((item) => {
        return item.productId != prodItem.productId
    })
    if (currentTab.value + 1 > prodList.value.length) {
        tabClick(currentTab.value - 1)
    }
}
const changeCurrent = (id: string) => {
    currentIndex.value = id;
}
const gotoWaitPage = () => {
    if(prodList.value[0].itemType === ItemType.Half){
        return gotoPage(prodList.value[0])
    }
    router.replace('/waitpage')
}
const unionConfirm = (item: ProdItem) => {
    gotoProd(item, '', ProdJumpDialogRef.value, true)
    clearProdItem(item);
}
const gotoPage = async (item: ProdItemEX) => {
    if(item.itemType === ItemType.Half && ProtocolRef.value){
        ProtocolRef.value.show(item.privacy[0].url, {
            orderId: item.orderId || '',
            itemOrderIds: JSON.stringify([item.productId]),
            approveUrl: item.detailUrl,
            apibItem: {
                infoId: item.infoId || '',
                orderId: '',
                orderItemId: item.productId,
                approveUrl: '',
                companyName: '',
                maxLoanAmount: '',
                minRate: '',
                maxRate: '',
                status: true,
                companyLogo: '',
                htmlContent: '',
                companySubTitle: '',
                companyTitle: '',
            }
        });
        return
    }
    getCacheApi({
        productId: item.productId
    })
    if (item.unionFlag) {
        UnionDialogRef.value?.show(item);
        return
    }
    await prodClickCountApi({ productId: item.productId });
    location.href = item.detailUrl
    clearProdItem(item);
}
const scrollToTarget = () => {
    setTimeout(() => {
        nextTick(() => {
            const targetElement = document.getElementById('page-title');
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
            } else {
                console.error('Target element not found');
            }
        })
    }, 500)
}
</script>

<style scoped lang="scss">
.page {
    display: flex;
    flex-direction: column;
    position: relative;
    background-image: url(src/assets/images/shop/bg.png);
    background-repeat: no-repeat;
    background-size: 100% auto;

    .custom-indicator {
        background: #FFFFFF;
        border-radius: 3px;
        margin-top: 6px;
        &-item {
            width: 14px;
            height: 4px;
            border-radius: 3px;
            background-color: #3879FC;
            transition: all 0.3s;
        }
    }

    &-grid {
        .four-shop {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 9px;
            margin: 8px 12px 0 12px;
            .current-active{
                transform: scale(1.02);
            }
            &-item {
                padding: 13px 7px 12px 7px;
                display: flex;
                flex-direction: column;
                border-radius: 12px;
                position: relative;
                transition: all 0.3s;
                >.item-corner{
                    display: flex;
                    position: absolute;
                    background: linear-gradient( 263deg, #FF7945 0%, #FF3638 100%);
                    border-radius: 0px 10px 0px 6px;
                    font-weight: 500;
                    font-size: 10px;
                    color: #FFFFFF;
                    line-height: 14px;
                    top: 0px;
                    right: 0px;
                    padding: 2px 6px;
                }
                >.item-bottom {
                    margin-top: 8px;
                    border-radius: 8px;
                    width: 100%;
                    padding: 9px 0;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    font-weight: 500;
                    font-size: 14px;
                    line-height: 20px;
                    color: #1277FF;
                    background-color: #fff;
                }

                >.item-body {
                    display: grid;
                    grid-template-columns: 1fr 1fr;
                    grid-template-rows: 1fr 1fr;
                    gap: 6px;
                    margin-top: 16px;

                    >div {
                        padding: 8px 7px 11px 7px;
                        border-radius: 8px;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;

                        >div:first-child {
                            font-weight: 400;
                            font-size: 12px;
                            line-height: 17px;
                        }

                        >div:last-child {
                            font-weight: 600;
                            font-size: 16px;
                            line-height: 25px;
                            white-space: nowrap;
                        }
                    }
                }

                >.item-head {
                    display: flex;
                    align-items: center;

                    >div {
                        >div:first-child {
                            font-size: 12px;
                            line-height: 17px;
                            font-weight: 600;
                            margin-bottom: 7px;
                        }

                        >div:last-child {
                            width: 100px;
                            font-size: 10px;
                            line-height: 14px;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            overflow: hidden;
                        }
                    }

                    >img {
                        width: 32px;
                        height: 32px;
                        margin-right: 6px;
                        border-radius: 4px;
                    }
                }
            }
        }
    }

    &-title {
        margin: 1px 12px 0 12px;
        font-size: 16px;
        color: #222222;
        line-height: 22px;
        display: flex;
        align-items: center;

        &-tips {
            margin-left: 4px;
            font-weight: 400;
            font-size: 12px;
            color: #999999;
            line-height: 17px;
        }
    }

    .gzh {
        background-color: rgba($color: #000000, $alpha: 0.8);
        padding: 13px 10px;
        margin: 8px 12px 10px 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-radius: 12px;

        &-tips {
            font-weight: 400;
            font-size: 10px;
            color: #FFFFFF;
            line-height: 14px;
            opacity: 0.7;
        }

        &-text {
            display: flex;
            align-items: center;
            font-weight: 600;
            font-size: 18px;
            color: #FFFFFF;
            line-height: 25px;

            &-box {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-left: 4px;
                border-radius: 4px;
                border: 1px solid #FFFFFF;
                font-weight: 600;
                font-size: 10px;
                color: #FFFFFF;
                line-height: 14px;
                padding: 0px 4px;
                height: 18px;
                white-space: nowrap;
                opacity: 0.72;
            }
        }

        &-img {
            width: 28px;
            height: 28px;
            margin-right: 10px;
            border-radius: 8px;
        }
    }

    .show-results {
        margin: 12px;
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;

        &-box {
            width: 100%;
            background: #FFFFFF;
            border-radius: 12px;
            padding: 14px 16px;
            display: flex;
            align-items: center;

            >img {
                width: 46px;
                height: 46px;
                margin-right: 12px;
            }

            .close-img {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background-color: #2c2e32;
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
                right: -8px;
                top: -8px;

                >img {
                    width: 12px;
                    height: 12px;
                }
            }

            .right-text {
                display: flex;
                flex-direction: column;

                &-title {
                    font-weight: 600;
                    font-size: 16px;
                    color: #222222;
                    line-height: 22px;
                    margin-bottom: 7px;
                }

                &-tips {
                    font-weight: 400;
                    font-size: 12px;
                    color: #666666;
                    line-height: 17px;
                }
            }
        }
    }

    &-body {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: flex-end;
        width: 100%;
        height: 566px;
        background-color: #fff;
        border-radius: 20px 20px 0 0;
        padding: 25px 16px 12px 16px;
        background: linear-gradient(181deg, #FFFFFF 50%, #D3E4FF 100%);
        position: relative;

        &-title {
            position: absolute;
            top: 25px;
            font-weight: bold;
            font-size: 24px;
            color: #1277FF;
            line-height: 35px;
            display: flex;
            flex-direction: column;
            align-items: center;

            .title-money {
                font-weight: bold;
                font-size: 38px;
                color: #FFFFFF;
                line-height: 47px;
                text-align: left;
                font-style: normal;
                background: linear-gradient(224.28382581991008deg, #FF8675 0%, #FF363B 100%);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
                position: relative;
                top: -2px;
            }
        }

        &-text {
            display: flex;
            align-items: center;
            font-weight: 400;
            font-size: 16px;
            color: #1277FF;
            line-height: 22px;
        }

        &-card-line {
            width: 100%;
            height: 4px;
            background: #A0C9FF;
            border-radius: 2px;
            position: relative;

            .point-style-box {
                position: absolute;
                width: 52px;
                height: 26px;
                left: calc(50% + 2px);
                top: -34px;

            }

            .line-point {
                display: flex;
                flex-direction: column;
                align-items: center;
                position: absolute;
                top: -6px;

                .box-lv1 {
                    background: #FFFFFF;
                    border: 1px solid #1277FF;
                }

                .box-lv2 {
                    background: #1277FF;
                    border: 1px solid #FFFFFF;
                }

                .box-lv3 {
                    background: #A0C9FF;
                    border: 1px solid #FFFFFF;
                }

                &-box {
                    width: 15px;
                    height: 15px;
                    margin-bottom: 8px;
                    border-radius: 50%;
                }

                &-text {
                    font-weight: 400;
                    font-size: 13px;
                    color: #2D496E;
                    line-height: 18px;
                }
            }
        }

        &-card-1 {
            width: 100%;
            height: 121px;
            background: #A7BAF1;
            border-radius: 16px;
            z-index: 2;
        }

        &-card-2 {
            width: 320px;
            height: 161px;
            background: #FFFFFF;
            border-radius: 16px;
            z-index: 2;
            position: absolute;
            padding: 21px 9px 0 9px;
        }

        &-card-3 {
            width: calc(100% - 32px);
            height: 100px;
            border-radius: 16px;
            z-index: 5;
            position: absolute;
            padding: 37px 32px 19px 32px;
            background-image: url(src/assets/images/shop/card-bottom.png);
            background-repeat: no-repeat;
            background-size: cover;
            display: flex;
            justify-content: center;
        }

        &-img-1 {
            position: absolute;
            width: 258px;
            height: 453px;
            z-index: 4;
        }

        &-img-2 {
            height: 440px;
            position: absolute;
            bottom: 110px;
        }

        &-iframe {
            width: 100%;
            border-radius: 20px;
        }
    }


    .msg-text {
        flex-direction: row;
        background-color: #fff;
        padding: 4px 12px;
        z-index: 1;
    }
}
</style>